{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# random_tsp"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/examples/random_tsp.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/python/random_tsp.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "Traveling Salesman Sample.\n",
    "\n",
    "   This is a sample using the routing library python wrapper to solve a\n",
    "   Traveling Salesman Problem.\n",
    "   The description of the problem can be found here:\n",
    "   http://en.wikipedia.org/wiki/Travelling_salesman_problem.\n",
    "   The optimization engine uses local search to improve solutions, first\n",
    "   solutions being generated using a cheapest addition heuristic.\n",
    "   Optionally one can randomly forbid a set of random connections between nodes\n",
    "   (forbidden arcs).\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import argparse\n",
    "from functools import partial\n",
    "import random\n",
    "\n",
    "from ortools.constraint_solver import routing_enums_pb2\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "parser = argparse.ArgumentParser()\n",
    "\n",
    "parser.add_argument(\n",
    "    '--tsp_size',\n",
    "    default=10,\n",
    "    type=int,\n",
    "    help='Size of Traveling Salesman Problem instance.')\n",
    "parser.add_argument(\n",
    "    '--tsp_use_random_matrix',\n",
    "    default=True,\n",
    "    type=bool,\n",
    "    help='Use random cost matrix.')\n",
    "parser.add_argument(\n",
    "    '--tsp_random_forbidden_connections',\n",
    "    default=0,\n",
    "    type=int,\n",
    "    help='Number of random forbidden connections.')\n",
    "parser.add_argument(\n",
    "    '--tsp_random_seed', default=0, type=int, help='Random seed.')\n",
    "\n",
    "# Cost/distance functions.\n",
    "\n",
    "\n",
    "def Distance(manager, i, j):\n",
    "    \"\"\"Sample function.\"\"\"\n",
    "    # Put your distance code here.\n",
    "    node_i = manager.IndexToNode(i)\n",
    "    node_j = manager.IndexToNode(j)\n",
    "    return node_i + node_j\n",
    "\n",
    "\n",
    "class RandomMatrix(object):\n",
    "    \"\"\"Random matrix.\"\"\"\n",
    "\n",
    "    def __init__(self, size, seed):\n",
    "        \"\"\"Initialize random matrix.\"\"\"\n",
    "\n",
    "        rand = random.Random()\n",
    "        rand.seed(seed)\n",
    "        distance_max = 100\n",
    "        self.matrix = {}\n",
    "        for from_node in range(size):\n",
    "            self.matrix[from_node] = {}\n",
    "            for to_node in range(size):\n",
    "                if from_node == to_node:\n",
    "                    self.matrix[from_node][to_node] = 0\n",
    "                else:\n",
    "                    self.matrix[from_node][to_node] = rand.randrange(\n",
    "                        distance_max)\n",
    "\n",
    "    def Distance(self, manager, from_index, to_index):\n",
    "        return self.matrix[manager.IndexToNode(from_index)][manager.IndexToNode(\n",
    "            to_index)]\n",
    "\n",
    "\n",
    "def main(args):\n",
    "    # Create routing model\n",
    "    if args.tsp_size > 0:\n",
    "        # TSP of size args.tsp_size\n",
    "        # Second argument = 1 to build a single tour (it's a TSP).\n",
    "        # Nodes are indexed from 0 to args_tsp_size - 1, by default the start of\n",
    "        # the route is node 0.\n",
    "        manager = pywrapcp.RoutingIndexManager(args.tsp_size, 1, 0)\n",
    "        routing = pywrapcp.RoutingModel(manager)\n",
    "        search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
    "        # Setting first solution heuristic (cheapest addition).\n",
    "        search_parameters.first_solution_strategy = (\n",
    "            routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC)\n",
    "\n",
    "        # Setting the cost function.\n",
    "        # Put a callback to the distance accessor here. The callback takes two\n",
    "        # arguments (the from and to node indices) and returns the distance between\n",
    "        # these indices.\n",
    "        cost = 0\n",
    "        if args.tsp_use_random_matrix:\n",
    "            matrix = RandomMatrix(args.tsp_size, args.tsp_random_seed)\n",
    "            cost = routing.RegisterTransitCallback(\n",
    "                partial(matrix.Distance, manager))\n",
    "        else:\n",
    "            cost = routing.RegisterTransitCallback(partial(Distance, manager))\n",
    "        routing.SetArcCostEvaluatorOfAllVehicles(cost)\n",
    "        # Forbid node connections (randomly).\n",
    "        rand = random.Random()\n",
    "        rand.seed(args.tsp_random_seed)\n",
    "        forbidden_connections = 0\n",
    "        while forbidden_connections < args.tsp_random_forbidden_connections:\n",
    "            from_node = rand.randrange(args.tsp_size - 1)\n",
    "            to_node = rand.randrange(args.tsp_size - 1) + 1\n",
    "            if routing.NextVar(from_node).Contains(to_node):\n",
    "                print('Forbidding connection ' + str(from_node) + ' -> ' +\n",
    "                      str(to_node))\n",
    "                routing.NextVar(from_node).RemoveValue(to_node)\n",
    "                forbidden_connections += 1\n",
    "\n",
    "        # Solve, returns a solution if any.\n",
    "        assignment = routing.Solve()\n",
    "        if assignment:\n",
    "            # Solution cost.\n",
    "            print(assignment.ObjectiveValue())\n",
    "            # Inspect solution.\n",
    "            # Only one route here; otherwise iterate from 0 to routing.vehicles() - 1\n",
    "            route_number = 0\n",
    "            node = routing.Start(route_number)\n",
    "            route = ''\n",
    "            while not routing.IsEnd(node):\n",
    "                route += str(node) + ' -> '\n",
    "                node = assignment.Value(routing.NextVar(node))\n",
    "            route += '0'\n",
    "            print(route)\n",
    "        else:\n",
    "            print('No solution found.')\n",
    "    else:\n",
    "        print('Specify an instance greater than 0.')\n",
    "\n",
    "\n",
    "main(parser.parse_args())\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
